package com.edfapp.costom;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author hong
 * @description 描述
 * @time 2025/9/25 15:09
 **/
public class TXTBrainWaveParser {
    // 正则表达式：匹配每行的【时间】和【BrainWave括号内的键值对】
    private static final Pattern DATA_PATTERN = Pattern.compile(
            "^(\\d{4}-\\d{2}-\\d{2}\\s+\\d{2}:\\d{2}:\\d{2}\\.\\d{3})\\s+BrainWave\\{(.*?)\\}$"
    );
    // 正则表达式：匹配键值对（如"att=38"）
    private static final Pattern KEY_VALUE_PATTERN = Pattern.compile("(\\w+)=([^,]+)");
    // 在写入前将数据缩放到合适的范围
//    private static final Double scaleFactor = 32767.0 / 3000000.0;
    /**
     * 解析脑波数据文件
     * @param filePath 文件路径（如"D:/data/a.txt"）
     * @return 结构化的BrainWave对象列表
     * @throws IOException  文件读取异常
     * @throws ParseException 数据格式异常
     */
    public List<TXTBrainWave> parseFile(String filePath) throws IOException, ParseException {
        List<TXTBrainWave> brainWaveList = new ArrayList<>();
        int lineNumber = 0;  // 记录行号，便于定位异常

        try (BufferedReader reader = new BufferedReader(new FileReader(filePath))) {
            String line;
            // 按行读取文件，直到末尾
            while ((line = reader.readLine()) != null) {
                lineNumber++;
                // 过滤空行或无效行（如非"E  BrainWave"开头的行）
                if (line.trim().isEmpty() || !line.contains("BrainWave")) {
                    continue;
                }
                // 解析单行数据为BrainWave对象
                TXTBrainWave brainWave = parseSingleLine(line, lineNumber);
                brainWaveList.add(brainWave);
            }
        }
        return brainWaveList;
    }

    /**
     * 解析单行文本为BrainWave对象
     * @param line 单行文本
     * @param lineNumber 行号（用于异常提示）
     * @return 结构化的BrainWave对象
     * @throws ParseException 数据格式异常
     */
    private TXTBrainWave parseSingleLine(String line, int lineNumber) throws ParseException {
        Matcher dataMatcher = DATA_PATTERN.matcher(line);
        // 验证行格式是否符合预期
        if (!dataMatcher.find()) {
            throw new ParseException("第" + lineNumber + "行格式错误：" + line);
        }

        TXTBrainWave brainWave = new TXTBrainWave();
        try {
            // 1. 解析采集时间（如"14:07:27.883"）
            String timeStr = dataMatcher.group(1);
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS");
            brainWave.setCollectTime(LocalDateTime.parse(timeStr, formatter));

            // 2. 解析BrainWave括号内的键值对（如"att=38, med=13,..."）
            String keyValueStr = dataMatcher.group(2);
            Matcher keyValueMatcher = KEY_VALUE_PATTERN.matcher(keyValueStr);

            // 遍历所有键值对，赋值到对象字段
            while (keyValueMatcher.find()) {
                String key = keyValueMatcher.group(1);  // 键（如"att"）
                String valueStr = keyValueMatcher.group(2);  // 值（如"38"）
                setFieldValue(brainWave, key, valueStr, lineNumber);
            }
        } catch (DateTimeParseException e) {
            throw new ParseException("第" + lineNumber + "行时间格式错误：" + e.getMessage());
        } catch (NumberFormatException e) {
            throw new ParseException("第" + lineNumber + "行数值格式错误：" + e.getMessage());
        } catch (IllegalArgumentException e) {
            throw new ParseException("第" + lineNumber + "行字段错误：" + e.getMessage());
        }

        return brainWave;
    }

    /**
     * 根据键名给BrainWave对象赋值
     * @param brainWave 目标对象
     * @param key 字段名（如"att"）
     * @param valueStr 字段值的字符串形式
     * @param lineNumber 行号
     */
    private void setFieldValue(TXTBrainWave brainWave, String key, String valueStr, int lineNumber) {
        switch (key) {
            case "signal":
                brainWave.setSignal(Integer.parseInt(valueStr));
                break;
            case "att":
                brainWave.setAtt(Double.parseDouble(valueStr));
                break;
            case "med":
                brainWave.setMed(Double.parseDouble(valueStr));
                break;
            case "delta":
                brainWave.setDelta(Double.parseDouble(valueStr));
                break;
            case "theta":
                brainWave.setTheta(Double.parseDouble(valueStr));
                break;
            case "lowAlpha":
                brainWave.setLowAlpha(Double.parseDouble(valueStr));
                break;
            case "highAlpha":
                brainWave.setHighAlpha(Double.parseDouble(valueStr));
                break;
            case "lowBeta":
                brainWave.setLowBeta(Double.parseDouble(valueStr));
                break;
            case "highBeta":
                brainWave.setHighBeta(Double.parseDouble(valueStr));
                break;
            case "lowGamma":
                brainWave.setLowGamma(Double.parseDouble(valueStr));
                break;
            case "middleGamma":
                brainWave.setMiddleGamma(Double.parseDouble(valueStr));
                break;
            case "ap":
                brainWave.setAp(Integer.parseInt(valueStr));
                break;
            case "batteryCapacity":
                brainWave.setBatteryCapacity(Integer.parseInt(valueStr));
                break;
            case "hardwareversion":
                brainWave.setHardwareVersion(Double.parseDouble(valueStr));
                break;
            case "grind":
                brainWave.setGrind(Integer.parseInt(valueStr));
                break;
            default:
                // 遇到未知字段时抛出异常，避免数据遗漏
                throw new IllegalArgumentException("未知字段：" + key);
        }
    }

    /**
     * 自定义解析异常类，用于区分解析错误与其他异常
     */
    public static class ParseException extends Exception {
        public ParseException(String message) {
            super(message);
        }
    }
}
